﻿using IM.Easy.ScheduledServices.IServices;
using Quartz;
using Quartz.Listener;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.ScheduledServices.Listener
{
    public class SchedulerListener : SchedulerListenerSupport
    {
        private readonly IScheduledJobService scheduledJobService;
        public SchedulerListener(IScheduledJobService scheduledJobService)
        {
            this.scheduledJobService = scheduledJobService;
        }

        /// <summary>
        /// 触发器完成时的操作
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task TriggerFinalized(ITrigger trigger, CancellationToken cancellationToken = default)
        {
            try
            {
                if (IsSingle(trigger)) return Task.CompletedTask;
                //修改任务状态
                var job = scheduledJobService.GetById(trigger.JobKey.Name);
                job.Status = Entity.Scheduled.SchedulerStatus.Completed;
                scheduledJobService.Update(job);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"系统异常{ex}");
                Console.ResetColor();
            }
            return Task.CompletedTask;
        }

        /// <summary>
        /// 判断是否单独执行计划
        /// </summary>
        /// <param name="trigger"></param>
        /// <returns></returns>
        private bool IsSingle(ITrigger trigger)
        {
            var match = trigger.JobDataMap.TryGetBoolean("single", out bool single);
            return match && single;
        }
    }
}
